import { computed, ref } from 'vue';
import { defineStore } from 'pinia';
import { getCurrentUser } from '@/api/user';
import type { LoginResponse } from '@/types/auth';
import type { UserProfile } from '@/types/user';

const TOKEN_STORAGE_KEY = 'tcm-ai-token';
const TOKEN_EXPIRES_KEY = 'tcm-ai-token-exp';

export const useAuthStore = defineStore('auth', () => {
  const token = ref<string | null>(localStorage.getItem(TOKEN_STORAGE_KEY));
  const tokenExpiresAt = ref<string | null>(localStorage.getItem(TOKEN_EXPIRES_KEY));
  const user = ref<UserProfile | null>(null);
  const initialized = ref(false);

  const isAuthenticated = computed(() => Boolean(token.value));

  function setToken(value: string | null, expiresAt?: string | null) {
    token.value = value;
    if (value) {
      localStorage.setItem(TOKEN_STORAGE_KEY, value);
    } else {
      localStorage.removeItem(TOKEN_STORAGE_KEY);
    }

    if (expiresAt) {
      tokenExpiresAt.value = expiresAt;
      localStorage.setItem(TOKEN_EXPIRES_KEY, expiresAt);
    } else {
      tokenExpiresAt.value = null;
      localStorage.removeItem(TOKEN_EXPIRES_KEY);
    }
  }

  function setUser(profile: UserProfile | null) {
    user.value = profile;
  }

  function setAuthResponse(payload: LoginResponse) {
    const headerToken = `${payload.tokenType} ${payload.token}`.trim();
    setToken(headerToken, payload.expiresAt ?? null);
    setUser(payload.user);
  }

  async function initialize() {
    if (initialized.value) {
      return;
    }
    initialized.value = true;
    if (!token.value) {
      return;
    }
    try {
      const profile = await getCurrentUser();
      setUser(profile);
    } catch (error) {
      clearAuth();
    }
  }

  function clearAuth() {
    setToken(null, null);
    setUser(null);
    initialized.value = false;
  }

  function logout() {
    clearAuth();
  }

  return {
    token,
    tokenExpiresAt,
    user,
    isAuthenticated,
    initialized,
    setAuthResponse,
    initialize,
    clearAuth,
    logout,
  };
});

